﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Web.DbHelper;

namespace KnowledgeCommunity.Web.Controllers
{
    public class CatalogController : Controller
    {
        CatalogHelper myCatalogHelper = new CatalogHelper();
        //
        // GET: /Catalog/
        [Authorize]
        public ActionResult Index()
        {
            string user = HttpContext.User.Identity.Name;
            var catalog = myCatalogHelper.SearchByUserName(user);
            ViewData["CatalogList"] = catalog;
            return View();
        }

        [Authorize]
        public ActionResult Details(int id)
        {
            var _Catalog = myCatalogHelper.FindById(id);
            return View(_Catalog);
        }

        [Authorize]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Create(Catalog model)
        {
            bool n = myCatalogHelper.Create(model);
            if (n)
                return Index();
            else
            {
                return RedirectToAction("Error", "Notice", new { type = 1 });
            }
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            var _Catalog = myCatalogHelper.FindById(id);
            return View(_Catalog);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Edit(Catalog model)
        {
            DoUpdateModel(model);
            return RedirectToAction("Details", new { id = model.Id });
        }

        [Authorize]
        public ActionResult Delete(int id)
        {
            var _Catalog = myCatalogHelper.FindById(id);
            return View(_Catalog);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            bool n = myCatalogHelper.Delete(id);
            if (n)
                return Index();
            else
                return RedirectToAction("Error", "Notice", new { type = 2 });
        }

        CKCDB mydb = new CKCDB();

        private void DoUpdateModel(Catalog model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var app = mydb.Catalogs.Find(model.Id);
                    UpdateModel(app);
                    mydb.SaveChanges();
                }
                catch (Exception ex)
                {
                    string message = "Create in table<Catalogs>" + ex.ToString();
                    WriteLog.WriteSysLog(message);
                }
            }
        }

    }
}
